import { Message } from "@arco-design/web-vue";

// 后端返回的数据类型
export interface uploadOptions<T> {
    data?: T
    code?: number
    status?: number
    msg?: string
}

/**
 * api请求封装
 * @param { String } url 请求地址
 * @param { Object } options useFtech第二个参数
 */

const yujiRequest = (url: string, options?: any) => {
    let router =  useRouter();
    const baseUrl = "http://pdf.lmptg.com";
    // url = baseUrl + url
    // const TOKEN = useCookie("userToken").value || ""
    const headers = {
        // TOKEN: TOKEN,
        ...options.headers,
    } // 设置默认请求头

    const body = new FormData();
    body.set("file", options.data.file)

    return new Promise(async (resolve, reject) => {
        const { data, error } = await useFetch(baseUrl + url,
            { method: options.method, headers, body: body })

        if (error.value) {
            let errorCode = error.value.data.code
            if(errorCode == 401){
                router.push('/login')
            }
            return reject(error.value)
        }
        const value = data.value as uploadOptions<any>

        if (!value) {
            console.log('后端接口报错', data.value);
            throw createError({
                statusCode: 500,
                statusMessage: url,
                message: '接口未知错误',
            })
        } else {
            if (value.code === 0) {
                // console.log("服务端错误", data.value);
                if (process.client) {
                    Message.error(value.msg)
                    resolve(data.value)
                }
            }else   if (value.code === 401) {
                router.push('/login')
                if (process.client) {
                    Message.error(value.msg)
                    resolve(data.value)
                }
            }
            else {
                if (value.status === 401) {
                    // 无权限
                    reject(value.msg)
                }
                else {
                    // 正常返回
                    resolve(data.value)
                }
            }
        }
    })
}

export default yujiRequest
